<template>
  <div>
    <h1>合同管理</h1>
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="员工编号">
        <el-input v-model="searchEmpNum" placeholder="请输入员工编号"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchByEmpNum">查询</el-button>
        <el-button type="success" @click="handleAdd">新增</el-button>
      </el-form-item>
    </el-form>

    <el-table border :data="tableData" style="width:100%">
      <el-table-column label="合同编号" prop="contractId" width="100" align="center" />
      <el-table-column label="员工编号" prop="empNum" width="100" align="center" />
      <el-table-column label="开始日期" prop="contractStartDate" width="160" align="center">
        <template slot-scope="scope">
          {{ scope.row.contractStartDate ? scope.row.contractStartDate.substring(0, 16) : '' }}
        </template>
      </el-table-column>
      <el-table-column label="结束日期" prop="contractEndDate" width="160" align="center">
        <template slot-scope="scope">
          {{ scope.row.contractEndDate ? scope.row.contractEndDate.substring(0, 16) : '' }}
        </template>
      </el-table-column>
      <el-table-column label="职位" prop="position" width="120" align="center" />
      <el-table-column label="部门" prop="department" width="120" align="center" />
      <el-table-column label="合同内容" prop="contractContent" min-width="200" show-overflow-tooltip />
      <el-table-column label="备注" prop="remarks" min-width="150" show-overflow-tooltip />
      <el-table-column label="操作" width="180" align="center" fixed="right">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" size="mini" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="员工编号" prop="empNum">
          <el-input v-model="form.empNum" placeholder="请输入员工编号" />
        </el-form-item>
        <el-form-item label="开始日期" prop="contractStartDate">
          <el-date-picker
            v-model="form.contractStartDate"
            type="datetime"
            placeholder="选择开始日期"
          />
        </el-form-item>
        <el-form-item label="结束日期" prop="contractEndDate">
          <el-date-picker
            v-model="form.contractEndDate"
            type="datetime"
            placeholder="选择结束日期"
          />
        </el-form-item>
        <el-form-item label="职位" prop="position">
          <el-input v-model="form.position" placeholder="请输入职位" />
        </el-form-item>
        <el-form-item label="部门" prop="department">
          <el-input v-model="form.department" placeholder="请输入部门" />
        </el-form-item>
        <el-form-item label="合同内容" prop="contractContent">
          <el-input
            type="textarea"
            v-model="form.contractContent"
            :rows="3"
            placeholder="请输入合同内容"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input
            type="textarea"
            v-model="form.remarks"
            :rows="2"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'ContractManage',
  data() {
    return {
      tableData: [],
      searchEmpNum: '',
      dialogVisible: false,
      dialogTitle: '新增合同',
      isEdit: false,
      currentContractId: null,
      form: {
        empNum: '',
        contractStartDate: '',
        contractEndDate: '',
        position: '',
        contractContent: '',
        remarks: '',
        department: ''
      },
      rules: {
        empNum: [{ required: true, message: '请输入员工编号', trigger: 'blur' }],
        contractStartDate: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
        contractEndDate: [{ required: true, message: '请选择结束日期', trigger: 'change' }],
        position: [{ required: true, message: '请输入职位', trigger: 'blur' }],
        contractContent: [{ required: true, message: '请输入合同内容', trigger: 'blur' }],
        department: [{ required: true, message: '请输入部门', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.$http.get('/api/employee_contracts')
        .then(response => {
          if (response.data.code === 200) {
            this.tableData = response.data.data
          } else {
            this.$message.error(response.data.msg)
          }
        })
    },

    searchByEmpNum() {
      if (!this.searchEmpNum) {
        this.getList()
        return
      }
      this.$http.get(`/api/employee_contracts/${this.searchEmpNum}`)
        .then(response => {
          if (response.data.code === 200) {
            this.tableData = response.data.data
          } else {
            this.$message.error(response.data.msg)
          }
        })
    },

    handleAdd() {
      this.isEdit = false
      this.dialogTitle = '新增合同'
      this.form = {
        empNum: '',
        contractStartDate: '',
        contractEndDate: '',
        position: '',
        contractContent: '',
        remarks: '',
        department: ''
      }
      this.dialogVisible = true
    },

    handleEdit(row) {
      this.isEdit = true
      this.dialogTitle = '编辑合同'
      this.currentContractId = row.contractId
      this.form = { ...row }
      this.dialogVisible = true
    },

    formatDate(date) {
      if (!date) return '';
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      const hours = String(d.getHours()).padStart(2, '0');
      const minutes = String(d.getMinutes()).padStart(2, '0');
      const seconds = String(d.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },

    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const config = {
            headers: {
              'Content-Type': 'application/json;charset=UTF-8'
            }
          };

          // 构造请求数据，格式化日期
          const data = {
            empNum: parseInt(this.form.empNum),
            contractStartDate: this.formatDate(this.form.contractStartDate),
            contractEndDate: this.formatDate(this.form.contractEndDate),
            position: this.form.position,
            contractContent: this.form.contractContent,
            remarks: this.form.remarks,
            department: this.form.department
          };

          if (this.isEdit) {
            this.$http.put(`/api/employee_contracts/${this.currentContractId}`, data, config)
              .then(response => {
                if (response.data.code === 200) {
                  this.$message.success('更新成功');
                  this.dialogVisible = false;
                  this.getList();
                } else {
                  this.$message.error(response.data.msg);
                }
              });
          } else {
            this.$http.post('/api/employee_contracts', data, config)
              .then(response => {
                if (response.data.code === 200) {
                  this.$message.success('添加成功');
                  this.dialogVisible = false;
                  this.getList();
                } else {
                  this.$message.error(response.data.msg);
                }
              });
          }
        }
      });
    },

    handleDelete(row) {
      this.$confirm('确认删除该合同记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete(`/api/employee_contracts/${row.contractId}`)
          .then(response => {
            if (response.data.code === 200) {
              this.$message.success('删除成功')
              this.getList()
            } else {
              this.$message.error(response.data.msg)
            }
          })
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.demo-form-inline {
  margin-bottom: 20px;
}
</style>
